<!--
 * @Author: songtao
 * @Date: 2021-11-04 18:13:04
 * @LastEditTime: 2021-11-22 15:58:17
 * @FilePath: \vue-cars\vue-admin\src\views\Login\index.vue
-->
<template>
    <div id="login">
        <div class="login-content">
            <ul>
                <li v-for="item in menuTab" :key="item.id" :class="{'isActive': item.isActive}" @click="tabChange(item)">{{item.text}}</li>
            </ul>
            <el-form :model="ruleForm" :rules="rules" ref="loginForm" class="login-form">
                <el-form-item prop="username">
                    <el-input size="mini" type="text" v-model="ruleForm.username" placeholder="邮箱"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input size="mini" type="password" v-model="ruleForm.password" placeholder="密码"></el-input>
                </el-form-item>
                <el-form-item prop="passwords" v-if="model === 'register'">
                    <el-input size="mini" type="password" v-model="ruleForm.passwords" placeholder="确认密码"></el-input>
                </el-form-item>
                <el-form-item prop="vcode">
                    <el-row :gutter="10">
                        <el-col :span="14">
                            <el-input size="mini" v-model="ruleForm.vcode" placeholder="验证码" ></el-input>
                        </el-col>
                        <el-col :span="10">
                            <el-button class="butBlock m-top4" type="success" size="mini" @click="getSms" :disabled="vCodeStates.isDisabled">{{vCodeStates.text}}</el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-button
                     :disabled="isDisabled"
                     type="primary" 
                     @click="submitForm('loginForm')" 
                     class="butBlock m-top20">
                     {{model === 'login' ? '登录' : '注册'}}
                </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script>
import sha1 from 'js-sha1'
import {GetSms , Register , Login} from "@/api/login.js"
import {onMounted, reactive , ref} from "@vue/composition-api"
import {stripscript , validateEmail } from '@/utils/validate'
export default {
    name:"login",
    setup(props, {refs,root}){
        let validateUsername = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入用户名'));
            } else if(!validateEmail(value)) {
                callback(new Error('用户名格式不正确'));
            } else {
                callback();
            }
        };
        let validatePassword = (rule, value, callback) => {
            ruleForm.password = stripscript(value)
            value = ruleForm.password
            let reg = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,20}$/;
            if (value === '') {
                callback(new Error('请输入密码'));
            } else if(!reg.test(value)){
                callback(new Error('密码格式不正确'));
            } else {
                callback();
            }
        };
        let validatePasswords = (rule, value, callback) => {
            ruleForm.passwords = stripscript(value)
            value = ruleForm.passwords
            let reg = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,20}$/;
            if (value === '') {
                callback(new Error('请输入密码'));
            } else if(!reg.test(value)){
                callback(new Error('密码格式不正确'));
            } else if(value !== ruleForm.password){
                 callback(new Error('确认密码跟密码不一致'));
            } else {
                callback();
            }
        };
        let validateVcode = (rule, value, callback) => {
            ruleForm.vcode = stripscript(value)
            value = ruleForm.vcode
            let reg = /^[a-z0-9]{6}$/;
            if (value === '') {
                callback(new Error('请输入验证码'));
            } else if(!reg.test(value)){
                callback(new Error('验证码格式不正确'));
            } else {
                callback();
            }
        }
        const menuTab = reactive([
            {text:"登录", isActive:true, type:"login"},
            {text:"注册", isActive:false, type:"register"}
        ])
        const model = ref('login')
        const isDisabled = ref(true)
        const vCodeStates = reactive({
            isDisabled: false,
            text:'获取验证码'
        })
        const timer = ref(null)
        let ruleForm = reactive({
          username: '522911345@qq.com',
          password: '123456a',
          passwords: '',
          vcode: ''
        })
        const rules = reactive({
          username: [
              { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
              { validator: validatePassword, trigger: 'blur' }
          ],
          passwords: [
              { validator: validatePasswords, trigger: 'blur' }
          ],
          vcode: [
              { validator: validateVcode, trigger: 'blur' }
          ]
        })
        
        // tabs切换登录跟注册
        const tabChange = (item => {
            menuTab.forEach(element => {
                element.isActive = false
            });
            // 高光
            item.isActive = true
            model.value = item.type
            clearDown()
            resetForm("loginForm")
        })

        // 获取验证码
        const getSms = (() => {
            if(ruleForm.username == ''){
                root.$message.error('邮箱不能为空');
                return false
            }else if(!validateEmail(ruleForm.username)){
                root.$message.error('邮箱格式不正确');
                return false
            }

            vCodeStates.isDisabled = true
            vCodeStates.text = '发送中'

            let _data = {
                username: ruleForm.username,
                module: model.value
            }
            setTimeout(() => {
                GetSms(_data).then(res => {
                    let data = res.data
                    if(data?.resCode === 0){
                        root.$message({
                            message: data.message,
                            type: 'success'
                        });
                    }
                    // 启用登录注册按钮
                    isDisabled.value = false
                    // 调用倒计时
                    countDown(5)
                }).catch(err => {
                    console.log(err)
                })
            },2000)

        })

        // 登录提交
        const submitForm = (formName => {
                // 注册
                refs[formName].validate((valid) => {
                    if (valid) {
                        let _data = {
                            username:ruleForm.username,
                            password:sha1(ruleForm.password),
                            code: ruleForm.vcode
                        }
                        if(model.value === "login"){
                            // 登录
                            root.$store.dispatch("app/login", _data).then((res) => {
                                root.$router.push({
                                    name:'Console'
                                })
                            }).catch((err) => {
                                console.log("登录失败，" , err)
                            })
                        }else{
                            // 注册
                            Register(_data).then(res => {
                                let data = res.data
                                if(data?.resCode === 0){
                                    // 注册完成之后
                                    tabChange(menuTab[0])
                                    clearDown()
                                    this.$message({
                                        message: data.message,
                                        type: 'success'
                                    })
                                }
                            }).catch(err => {})
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
        })

        // 重置表单
        const resetForm = (formName =>{
            refs[formName].resetFields();
        })

        // 倒计时
        const countDown = ((number) => {
            // 判断定时器是否存在，存在就清除
            if(timer.value){ clearInterval(timer.value) }
            // setTimeout 至执行一次 ;  setInterval 不断执行，需要条件才会停止
            let time = number
            timer.value = setInterval(() => {
                time--
                if(time === 0){
                    clearInterval(timer.value)
                    vCodeStates.isDisabled = false
                    vCodeStates.text = '再次获取'
                }else{
                    vCodeStates.text = `倒计时${time}秒`
                }
            },1000)
        })

        // 清除倒计时
        const clearDown = (() => {
            // 还原验证码按钮的默认状态
            vCodeStates.isDisabled = false
            vCodeStates.text = '获取验证码'
            // 清除计时器
            clearInterval(timer.value)
        }) 

        onMounted(() => {})
        
        return {
            menuTab,
            model,
            isDisabled,
            vCodeStates,
            timer,
            ruleForm,
            rules,
            tabChange,
            submitForm,
            getSms,
            resetForm,
            clearDown
        }
    }
}
</script>
<style lang="scss" scoped>
#login {
    height: 100vh;
    background-color:#344a5f;
    .login-content{
        width: 20%;
        position: absolute;
        top: 40%;
        left: 0;
        right: 0;
        margin: auto;
        margin-top: -100px;
        ul{
            margin-bottom: 20px;
            li{
                display: inline-block;
                text-align: center;
                width: 50%;
                height: 30px;
                line-height: 30px;
                color: #fff;
                border-radius: 3px;
                cursor: pointer;
            }
            .isActive{
                background-color: rgba(255,255,255,0.5);
            }
        }
        /deep/.el-form-item__error{
            top: 25% !important;
            right: -45% !important;
            left: 105% !important;
        }
        /deep/.el-form-item__label{
            color: #fff;
        }
        /deep/.el-input__inner{
            font-size: 10px;
        }
    }
    .login-form{
        .butBlock{
            display: block;
            width: 100%;
        }
        .m-top20{
            margin-top: 20px;
        }
        .m-top4{
            margin-top: 4px;
        }
    }
}
</style>